package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLOrder;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.adapter.AppraiseAdapter;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_like_poeple)
public class Appraise extends BaseActivity implements OnRefreshListener,
        OnLoadListener, OnItemClickListener {

    private AutoListView appraiseListview = null;
    private AppraiseAdapter appraiseAdapter;
    private List<MLOrder> myOrderList = new ArrayList<MLOrder>();
    private LinearLayout linBlank;
    private TextView tvBlankNoLove;
    private TextView tvBlankBg;
    private HeaderLayout header;
    private LoadingDailog mLoadingDialog;
    public static final int BEGIN_TO_LOADING = -1;
    private int skipDataCount = 0; // 忽略前N个对象
    public static final int MORE_DATA_MAX_COUNT = 20; // 每页10个对象
    private boolean isUpdateList = false; // 是否刷新列表
    private MLUser mlUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        mlUser = UserService.getCurrentUser();
        initView();
        setHeaderFunction();
        mLoadingDialog = ToolKits.createLoadingDialog(Appraise.this, "登陆中...");
        mLoadingDialog.setText("加载中");
        getOrderList(AutoListView.REFRESH);

        // initListview();
    }

    private void initView() {
        appraiseListview = (AutoListView) findViewById(R.id.id_stickynavlayout_innerscrollview);
        linBlank = (LinearLayout) findViewById(R.id.linBlankNoLove);
        tvBlankNoLove = (TextView) findViewById(R.id.tvBlankNoLove);
        tvBlankBg = (TextView) findViewById(R.id.tvBlankBg);
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        appraiseAdapter = new AppraiseAdapter(this, myOrderList);
        appraiseListview.setAdapter(appraiseAdapter);
        appraiseAdapter.notifyDataSetChanged();
        appraiseListview.setPageSize(MORE_DATA_MAX_COUNT);
        // likePeopleListview.setOnRefreshListener(this);
        appraiseListview.setOnLoadListener(this);
        appraiseListview.setOnItemClickListener(this);
    }

    public void setHeaderFunction() {
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        header.init(HeaderStyle.IMG_TITLE_TEXT);
        header.setMiddleText("评价");
        header.setRightText("");
        header.setLeftContainerClickListener(new onLeftContainerListener() {
            @Override
            public void onClick() {
                Appraise.this.finish();
            }
        });
    }

    /*
     * 请求最近在线对象
     */
    private void getOrderList(final int what) {
        // mLoadingDialog.show();
        linBlank.setVisibility(View.GONE);
        // Log.e("==userPreferences===", "userPreferences本地有点赞纪录");
        if (what != BEGIN_TO_LOADING) {
            isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新
        } else {
            appraiseListview.setRefreshData(); // 初始化显示loading动态图片
        }
        if (myOrderList == null || myOrderList.size() <= 0 || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud

            final AVQuery<MLOrder> query = new AVQuery<MLOrder>("MLOrder");
            skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
            if (what != AutoListView.LOAD) {
                skipDataCount = 0; // 刷新时不用忽略前面对象
            }
            query.include("winner");
            query.whereEqualTo("sponsor", UserService.getCurrentUser());
            query.setSkip(skipDataCount); // 忽略前N个
            query.whereGreaterThan("status", 1);
            query.orderByDescending("updatedAt");
            query.whereLessThan("status", 4);
            query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
            query.findInBackground(new FindCallback<MLOrder>() {

                @Override
                public void done(List<MLOrder> orderList, AVException arg1) {
                    // mLoadingDialog.dismiss();
                    if (arg1 == null) {
                        // Log.e("===userId==",
                        // "userPreferences:"
                        // + String.valueOf(userList.size()));
                        if (orderList.size() <= 0) {
                            if (what != AutoListView.LOAD) {
                                tvBlankBg
                                        .setBackgroundResource(R.drawable.new_lover);
                                tvBlankNoLove.setText(getResources().getString(
                                        R.string.blank_no_new_comment));
                                linBlank.setVisibility(View.VISIBLE);
                                tvBlankNoLove.setVisibility(View.VISIBLE);
                            }
                            appraiseListview.setNoData();

                        } else {
                            linBlank.setVisibility(View.GONE);

                            // int listViewHeight = ViewUtil
                            // .setListViewHeightBasedOnChildren1(likePeopleListview);
                            switch (what) {
                                case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
                                    myOrderList = orderList;
                                    appraiseListview.onRefreshComplete();
                                    // onLineListAdapter.setDatas(userList);
                                    break;
                                case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
                                    appraiseListview.onLoadComplete();
                                    myOrderList.addAll(orderList);
                                    break;
                                case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
                                    myOrderList = orderList;
                                    appraiseListview.onRefreshComplete();
                                    // onLineListAdapter.setDatas(userList);
                                    break;
                            }
                            appraiseListview.setResultSize(myOrderList.size());
                            appraiseAdapter.setDatas(myOrderList);
                            appraiseAdapter.notifyDataSetChanged();
                            isUpdateList = false; // 刷新完毕，设为false
                        }
                    } else {
                        // Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());
                        appraiseListview.setNoData();
                        if (myOrderList.size() <= 0) {

                            linBlank.setVisibility(View.VISIBLE);
                            tvBlankBg
                                    .setBackgroundResource(R.drawable.network_error);
                            tvBlankNoLove.setText(getResources().getString(
                                    R.string.blank_network_error));
                            linBlank.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    getOrderList(BEGIN_TO_LOADING);
                                }
                            });
                        } else {
                            ToolKits.toast(Appraise.this, "网络错误");
                        }
                    }
                }
            });

        } else {
            // mLoadingDialog.dismiss();
            linBlank.setVisibility(View.VISIBLE);
            // userLikeList = null;
            // appraiseAdapter.setDatas(userLikeList);
            // appraiseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        if (position - 1 < 0 || appraiseAdapter.getCount() <= 0 || position - 1 >= appraiseAdapter.getCount()) {
            return;
        }
        MLOrder mlOrder = (MLOrder) appraiseAdapter.getItem(position - 1);
        String selectedUserId = mlOrder.getWinner().getObjectId();
        Intent intent = new Intent(Appraise.this, Profile.class);
        intent.putExtra("userId", selectedUserId);
        intent.putExtra("nickname", mlOrder.getWinner().getNickname());
        startActivity(intent);

    }

    @Override
    public void onLoad() {
        // TODO Auto-generated method stub
        getOrderList(AutoListView.LOAD);

    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        getOrderList(AutoListView.REFRESH);
        appraiseListview.setOnRefreshListener(this);
    }
}